import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { state } from '@/stores/localstorage'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      children: [
        // 前台页面
        {
          path: 'frontend',
          name: 'FrontendLayout',
          component: () => import('@/views/frontend/FrontendLayout.vue'),
          children: [
            // 博客的列表页
            {
              path: 'blog/list',
              name: 'FrontendBlogList',
              component: () => import('@/views/frontend/BlogList.vue')
            }
          ]
        },
        // 后台页面
        {
          path: 'backend',
          name: 'BackendLayout',
          component: () => import('@/views/backend/BackendLayout.vue'),
          children: [
            // 后台导航页
            {
              path: 'admin',
              name: 'Admin',
              component: () => import('@/views/backend/AdminView.vue')
            },
            {
              path: 'blog',
              name: 'BackendBlogList',
              component: () => import('@/views/backend/blog/BlogList.vue')
            },
            {
              path: 'blog/create',
              name: 'BackendBlogCreate',
              component: () => import('@/views/backend/blog/BlogCreate.vue')
            },
            {
              path: 'tag',
              name: 'TagList',
              component: () => import('@/views/backend/tag/TagList.vue')
            },
            {
              path: 'comment',
              name: 'CommentList',
              component: () => import('@/views/backend/comment/CommentList.vue')
            }
          ]
        },
        // 403 页面
        {
          path: 'errors/403',
          name: 'PermissionDeny',
          component: () => import('@/views/errors/PermissionDeny.vue')
        },
        // 404 页面
        {
          path: '/:pathMatch(.*)*',
          name: 'NotFound',
          component: () => import('@/views/errors/NotFound.vue')
        }
      ]
    },
    // login 页面
    {
      path: '/login',
      name: 'LoginPage',
      component: () => import('@/views/login/LoginPage.vue')
    }
  ]
})

router.beforeEach((to) => {
  if (to.name == 'LoginPage' && state.value.isLogin) {
    return { name: 'BackendBlogList' }
  }
  if (to.path.match('^/backend.*') && !state.value.isLogin) {
    // 记录下用户需要去的真正页面
    return { name: 'LoginPage', query: { to: to.name } }
  }
  if (to.name == 'home') {
    return { name: 'BackendBlogList' }
  }
})

export default router
